<template>
  <el-container>
    <aside-layout></aside-layout>
    <el-main>
      <div class="header">
        <h2>外出登记管理</h2>
        <el-button type="primary" icon="el-icon-plus" @click="addRegistration">新增登记</el-button>
      </div>

      <!-- 外出申请审批模块 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="24">
          <el-card shadow="hover" class="card">
            <div slot="header" class="clearfix">
              <span>外出申请审批</span>
            </div>
            <el-table :data="pendingApprovals" style="width: 100%" border stripe>
              <el-table-column prop="registrationNumber" label="登记编号" width="150"></el-table-column>
              <el-table-column prop="elderlyName" label="老人姓名" width="150"></el-table-column>
              <el-table-column prop="outingDate" label="外出日期" width="150">
                <template slot-scope="scope">
                  {{ new Date(scope.row.outingDate).toLocaleDateString() }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                  <el-button type="success" @click="approve(scope.row)">批准</el-button>
                  <el-button type="danger" @click="reject(scope.row)">拒绝</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

      <!-- 外出历史记录模块 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="24">
          <el-card shadow="hover" class="card">
            <div slot="header" class="clearfix header">
              <span>外出历史记录</span>
              <el-button type="primary" icon="el-icon-plus" @click="addHistory" class="header-button">新增历史记录</el-button>
            </div>
            <ul class="history-list">
              <li v-for="(history, index) in outingHistory" :key="index" class="history-item">
                {{ history.history }}
                <div class="button-group">
                  <el-button type="text" @click="editHistory(history)">编辑</el-button>
                  <el-button type="danger" @click="deleteHistory(history.id)">删除</el-button>
                </div>
              </li>
            </ul>
          </el-card>
        </el-col>
      </el-row>

      <!-- 外出安全提示模块 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="24">
          <el-card shadow="hover" class="card">
            <div slot="header" class="clearfix header">
              <span>外出安全提示</span>
              <el-button type="primary" icon="el-icon-plus" @click="addTip" class="header-button">新增安全提示</el-button>
            </div>
            <ul class="safety-tips">
              <li v-for="(tip, index) in safetyTips" :key="index" class="safety-item">
                <i class="el-icon-info safety-icon"></i>
                {{ tip.tip }}
                <div class="button-group">
                  <el-button type="text" @click="editTip(tip)">编辑</el-button>
                  <el-button type="danger" @click="deleteTip(tip.id)">删除</el-button>
                </div>
              </li>
            </ul>
          </el-card>
        </el-col>
      </el-row>

      <!-- 新增/编辑外出登记对话框 -->
      <el-dialog :title="registrationDialogTitle" :visible.sync="registrationDialogVisible" width="50%">
        <el-form :model="registrationForm" label-width="120px">
          <el-form-item label="登记编号">
            <el-input v-model="registrationForm.registrationNumber" placeholder="请输入登记编号"></el-input>
          </el-form-item>
          <el-form-item label="老人姓名">
            <el-input v-model="registrationForm.elderlyName" placeholder="请输入老人姓名"></el-input>
          </el-form-item>
          <el-form-item label="外出原因">
            <el-input v-model="registrationForm.outingReason" placeholder="请输入外出原因"></el-input>
          </el-form-item>
          <el-form-item label="外出日期">
            <el-date-picker v-model="registrationForm.outingDate" type="date" placeholder="选择日期" style="width: 100%;"></el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="registrationDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleRegistrationSubmit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 新增/编辑外出历史记录对话框 -->
      <el-dialog :title="historyDialogTitle" :visible.sync="historyDialogVisible" width="50%">
        <el-form :model="historyForm" label-width="120px">
          <el-form-item label="历史记录">
            <el-input v-model="historyForm.history" placeholder="请输入历史记录"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="historyDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleHistorySubmit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 新增/编辑外出安全提示对话框 -->
      <el-dialog :title="tipDialogTitle" :visible.sync="tipDialogVisible" width="50%">
        <el-form :model="tipForm" label-width="120px">
          <el-form-item label="安全提示">
            <el-input v-model="tipForm.tip" placeholder="请输入安全提示"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="tipDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleTipSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import AsideLayout from '@/layout/asideLayout.vue'
import axios from 'axios'

export default {
  name: 'OutingRegistration',
  components: {
    AsideLayout
  },
  data() {
    return {
      pendingApprovals: [],
      outingHistory: [],
      safetyTips: [],
      registrationDialogVisible: false,
      registrationDialogTitle: '',
      registrationForm: {
        id: null,
        registrationNumber: '',
        elderlyName: '',
        outingReason: '',
        outingDate: '',
        status: '待审批'
      },
      historyDialogVisible: false,
      historyDialogTitle: '',
      historyForm: {
        id: null,
        history: ''
      },
      tipDialogVisible: false,
      tipDialogTitle: '',
      tipForm: {
        id: null,
        tip: ''
      }
    }
  },
  mounted() {
    this.fetchPendingApprovals()
    this.fetchOutingHistory()
    this.fetchSafetyTips()
  },
  methods: {
    fetchPendingApprovals() {
      axios.get('http://localhost:3000/api/outing-registrations')
        .then(response => {
          this.pendingApprovals = response.data.filter(registration => registration.STATUS === '待审批')
        })
        .catch(error => {
          console.error('Error fetching pending approvals:', error)
        })
    },
    fetchOutingHistory() {
      axios.get('http://localhost:3000/api/outing-history')
        .then(response => {
          this.outingHistory = response.data
        })
        .catch(error => {
          console.error('Error fetching outing history:', error)
        })
    },
    fetchSafetyTips() {
      axios.get('http://localhost:3000/api/safety-tips')
        .then(response => {
          this.safetyTips = response.data
        })
        .catch(error => {
          console.error('Error fetching safety tips:', error)
        })
    },
    addRegistration() {
      this.registrationDialogTitle = '新增登记'
      this.registrationForm = {
        id: null,
        registrationNumber: '',
        elderlyName: '',
        outingReason: '',
        outingDate: '',
        status: '待审批'
      }
      this.registrationDialogVisible = true
    },
    approve(row) {
      axios.put(`http://localhost:3000/api/outing-registrations/${row.id}`, { ...row, STATUS: '已批准' })
        .then(() => {
          this.fetchPendingApprovals()
          this.$message.success(`批准成功，登记编号：${row.registrationNumber}`)
        })
        .catch(error => {
          console.error('Error approving registration:', error)
          this.$message.error('批准失败')
        })
    },
    reject(row) {
      axios.put(`http://localhost:3000/api/outing-registrations/${row.id}`, { ...row, STATUS: '已拒绝' })
        .then(() => {
          this.fetchPendingApprovals()
          this.$message.success(`拒绝成功，登记编号：${row.registrationNumber}`)
        })
        .catch(error => {
          console.error('Error rejecting registration:', error)
          this.$message.error('拒绝失败')
        })
    },
    handleRegistrationSubmit() {
      if (this.registrationForm.id) {
        axios.put(`http://localhost:3000/api/outing-registrations/${this.registrationForm.id}`, {
          ...this.registrationForm,
          STATUS: this.registrationForm.status
        })
          .then(() => {
            this.fetchPendingApprovals()
            this.registrationDialogVisible = false
            this.$message.success('更新登记成功')
          })
          .catch(error => {
            console.error('Error updating registration:', error)
            this.$message.error('更新登记失败')
          })
      } else {
        axios.post('http://localhost:3000/api/outing-registrations', this.registrationForm)
          .then(() => {
            this.fetchPendingApprovals()
            this.registrationDialogVisible = false
            this.$message.success('新增登记成功')
          })
          .catch(error => {
            console.error('Error adding registration:', error)
            this.$message.error('新增登记失败')
          })
      }
    },
    addHistory() {
      this.historyDialogTitle = '新增历史记录'
      this.historyForm = {
        id: null,
        history: ''
      }
      this.historyDialogVisible = true
    },
    editHistory(history) {
      this.historyDialogTitle = '编辑历史记录'
      this.historyForm = { ...history }
      this.historyDialogVisible = true
    },
    handleHistorySubmit() {
      if (this.historyForm.id) {
        axios.put(`http://localhost:3000/api/outing-history/${this.historyForm.id}`, this.historyForm)
          .then(() => {
            this.fetchOutingHistory()
            this.historyDialogVisible = false
            this.$message.success('更新历史记录成功')
          })
          .catch(error => {
            console.error('Error updating history:', error)
            this.$message.error('更新历史记录失败')
          })
      } else {
        axios.post('http://localhost:3000/api/outing-history', this.historyForm)
          .then(() => {
            this.fetchOutingHistory()
            this.historyDialogVisible = false
            this.$message.success('新增历史记录成功')
          })
          .catch(error => {
            console.error('Error adding history:', error)
            this.$message.error('新增历史记录失败')
          })
      }
    },
    addTip() {
      this.tipDialogTitle = '新增安全提示'
      this.tipForm = {
        id: null,
        tip: ''
      }
      this.tipDialogVisible = true
    },
    editTip(tip) {
      this.tipDialogTitle = '编辑安全提示'
      this.tipForm = { ...tip }
      this.tipDialogVisible = true
    },
    handleTipSubmit() {
      if (this.tipForm.id) {
        axios.put(`http://localhost:3000/api/safety-tips/${this.tipForm.id}`, this.tipForm)
          .then(() => {
            this.fetchSafetyTips()
            this.tipDialogVisible = false
            this.$message.success('更新安全提示成功')
          })
          .catch(error => {
            console.error('Error updating tip:', error)
            this.$message.error('更新安全提示失败')
          })
      } else {
        axios.post('http://localhost:3000/api/safety-tips', this.tipForm)
          .then(() => {
            this.fetchSafetyTips()
            this.tipDialogVisible = false
            this.$message.success('新增安全提示成功')
          })
          .catch(error => {
            console.error('Error adding tip:', error)
            this.$message.error('新增安全提示失败')
          })
      }
    },
    deleteHistory(id) {
      axios.delete(`http://localhost:3000/api/outing-history/${id}`)
        .then(() => {
          this.fetchOutingHistory()
          this.$message.success('删除历史记录成功')
        })
        .catch(error => {
          console.error('Error deleting history:', error)
          this.$message.error('删除历史记录失败')
        })
    },
    deleteTip(id) {
      axios.delete(`http://localhost:3000/api/safety-tips/${id}`)
        .then(() => {
          this.fetchSafetyTips()
          this.$message.success('删除安全提示成功')
        })
        .catch(error => {
          console.error('Error deleting tip:', error)
          this.$message.error('删除安全提示失败')
        })
    }
  }
}
</script>

<style scoped>
.card {
  border-radius: 8px;
  overflow: hidden;
}

.el-main {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-button {
  margin-left: auto;
}

.history-list, .safety-tips {
  list-style: none;
  padding: 0;
}

.history-list li, .safety-tips li {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.safety-icon {
  font-size: 18px;
  color: #409EFF;
  margin-right: 10px;
}

.history-item, .safety-item {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f9f9f9;
  transition: background-color 0.3s;
}

.history-item:hover, .safety-item:hover {
  background-color: #f1f1f1;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>